package com.zhou.base.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 18576666986
 * @description zxf
 * @createDate 2022/7/12 13:55
 */
@Configuration
public class JacksonConfig {

    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {

        return builder -> {

            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)));
            builder.deserializerByType(LocalDateTime.class, new CombinedLocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern)));
            builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));
            builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));
        };
    }

    class CombinedLocalDateTimeDeserializer extends LocalDateTimeDeserializer {
        public CombinedLocalDateTimeDeserializer(DateTimeFormatter dtf) {
            super(dtf);
        }

        @Override
        public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
            try {
                String str = parser.getText().trim();
                return LocalDateTime.parse(str, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            } catch (DateTimeException ex) {
                return super.deserialize(parser, context);
            }
        }
    }

/*    //jackson xmlObject 对 xml 进行序列化和反序列化
    @Autowired
    private Jackson2ObjectMapperBuilder builder;
    private ObjectMapper xmlMapper;
    public void afterPropertiesSet() throws Exception {
        xmlMapper = builder.createXmlMapper(true).build();
    }*/


}
